package org.csu.leiyun.demo.persistence;

import org.csu.leiyun.demo.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

@Repository
public class AccountDAOImpl implements AccountDAO{
    @Autowired
    private DataSource dataSource; //通过数据源方式连接数据库
    @Override
    public Account findByUsernameAndPassword(Account account) {
        Account loginAccount=null;
        try {
            Connection connection=dataSource.getConnection();
            PreparedStatement pStatement=connection.prepareStatement(FIND_BY_USERNAME_AND_PASSWORD);//设置执行语句
            pStatement.setString(1,account.getUsername());
            pStatement.setString(2,account.getPassword());
            ResultSet resultSet = pStatement.executeQuery();//执行查询语句获取查询结果
            if (resultSet.next()){
                loginAccount = new Account();
                //获取用户信息
                loginAccount.setId(resultSet.getInt("id"));
                loginAccount.setUsername(resultSet.getString("name"));
                loginAccount.setPassword(resultSet.getString("password"));
                loginAccount.setAge(resultSet.getInt("age"));
                loginAccount.setGender(resultSet.getInt("gender"));
                loginAccount.setEmail(resultSet.getString("email"));
            }
            resultSet.close();
            pStatement.close();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return loginAccount;
    }
    @Override
    public ArrayList<Account> findAll(){
        ArrayList<Account> accountArrayList = new ArrayList<>();
        try {
            Connection connection=dataSource.getConnection();
            PreparedStatement pStatement=connection.prepareStatement(FIND_ALL);//设置执行语句
            ResultSet resultSet = pStatement.executeQuery();//执行查询语句获取查询结果
            while (resultSet.next()){
                Account account = new Account();
                //获取用户信息
                account.setId(resultSet.getInt("id"));
                account.setUsername(resultSet.getString("name"));
                account.setPassword(resultSet.getString("password"));
                account.setAge(resultSet.getInt("age"));
                account.setGender(resultSet.getInt("gender"));
                account.setEmail(resultSet.getString("email"));
                accountArrayList.add(account);
            }
            resultSet.close();
            pStatement.close();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return accountArrayList;

    }
}
